
package org.catpay.modules.sys.service.impl;

import java.awt.image.BufferedImage;

import org.apache.commons.lang.StringUtils;
import org.catpay.common.exception.RRException;
import org.catpay.common.utils.RedisUtils;
import org.catpay.modules.sys.service.SysCaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.code.kaptcha.Producer;

/**
 * 验证码
 *
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl implements SysCaptchaService {
	@Autowired
	private Producer producer;

	@Value("${spring.redis.expire}")
	private long expire;

	@Autowired
	private RedisUtils redisUtils;

	@Override
	public BufferedImage getCaptcha(String uuid) {
		if (StringUtils.isBlank(uuid)) {
			throw new RRException("uuid不能为空");
		}
		// 生成文字验证码
		String code = producer.createText();
		if (StringUtils.isNotBlank(redisUtils.get(uuid)))
			throw new RRException("该uuid的验证码已存在");
		else
			redisUtils.set(uuid, code, expire);

		return producer.createImage(code);
	}

	@Override
	public void validate(String uuid, String code) {
		String c = redisUtils.get(uuid);
		if (StringUtils.isBlank(c))
			throw new RRException("验证码已过期");
		if (!code.equalsIgnoreCase(c))
			throw new RRException("验证码错误");
		redisUtils.delete(uuid);
	}
}
